require.config({
    paths: {
        'columntoggle': '../addons/facrm/js/columntoggle',
    }
});
define(['jquery', 'bootstrap', 'backend', 'table', 'form','columntoggle'], function ($, undefined, Backend, Table, Form,Columntoggle) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/customer/contacts/index',
                    add_url: 'facrm/customer/contacts/add',
                    edit_url: 'facrm/customer/contacts/edit',
                    del_url: 'facrm/customer/contacts/del'
                }
            });

            //联系人
            var contact  = $("#customer_contacts");
            //在普通搜索渲染后
            contact.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='owner_user_id']", form).addClass("selectpage").data("source", "facrm/common/selectpage/model/admin?type=children").data("primaryKey", "id").data("field", "nickname").data("orderBy", "id desc");
                $("input[name='customer_id']", form).addClass("selectpage").data("source", "facrm/customer/index?filter=%7B\"scene_id\"%3A\"1\"%7D").data("primaryKey", "id").data("field", "name").data("orderBy", "id desc");
                $(".commonsearch-table select[name=scene_id]").val(4);
            });
            var columnss=[
                {checkbox: true},
                {
                    field: 'scene_id',
                    title: __('联系人场景'),
                    visible: false,
                    formatter: function (v,r) {
                        return scene_list[v];
                    },searchList: scene_list},
                {
                    field: 'customer_id',
                    title: __('客户名称'),
                    operate: "LIKE",
                    align: 'left',
                    formatter: function (value, row, index) {
                        if(!row.customer) return '-';
                        value='<a href="javascript:void(0);" data-url="facrm/customer/index/detail/ids/' + row.customer_id
                            +'" data-area="[&quot;100%&quot;,&quot;100%&quot;]" class="btn-dialog" data-title="'+ row.customer.name+'">'+ row.customer.name +'('+row.customer_id+')'+'</a>';
                        return value;
                    },
                    addclass: 'selectpage',
                    extend: 'data-source="facrm/customer/index?filter=%7B\"scene_id\"%3A\"1\"%7D" data-field="name" data-orderBy="id desc"'},
                {field: 'name', title: __('姓名')},
                {field: 'mobile', title: __('手机')},
                {field: 'telephone', title: __('电话')},
                {field: 'email', title: __('邮箱')},
                {field: 'wechat', title: __('微信')},
                {field: 'post', title: __('职务')},
                {field: 'sex', title: __('性别'),searchList: {'-1':"未知",'0':'女','1':'男'},formatter:Table.api.formatter.status},
                {field: 'decision', title: __('决策人'),searchList: {'-1':"未知","0":"否",'1':'是'},formatter:Table.api.formatter.status},
                {field: 'detail_address', title: __('地址')},
                {field: 'remark', title: __('备注')},
                {field: 'next_time', title: __('下次联系'),formatter:Table.api.formatter.datetime, operate:'RANGE',addclass:'datetimerange' ,sortable: true},
                {field: 'create_time', title: __('创建时间'),formatter:Table.api.formatter.datetime, operate:'RANGE',addclass:'datetimerange' ,sortable: true},
                {field: 'owner_user.nickname', title: __('负责人'), operate: false, search: false},
                {field: 'owner_user_id', title: __('负责人'), visible: false,
					addclass: 'selectpage',
					extend: 'data-source="facrm/common/selectpage/model/admin?type=children" data-field="nickname" data-orderBy="id desc"'},
                {field: 'operate', title: __('Operate'), table: contact,
                    events: Table.api.events.operate,
                    buttons: [
                        {
                            name: 'edit',
                            text: '',
                            title: '修改联系人',
                            icon: 'fa fa-pencil',
                            classname: 'btn btn-xs btn-success  btn-dialog',
                            url: 'facrm/customer/contacts/edit',

                        },
                        {name: 'del',
                            text: '',
                            title: '删除',
                            confirm:"确认删除联系人？",
                            icon: 'fa fa-trash',
                            classname: 'btn btn-xs btn-danger  btn-ajax',
                            url: 'facrm/customer/contacts/del',
                            success:function(data,ret){
                                $("a.btn-refresh").trigger("click");
                            },
                        },
                        {
                            name: 'email',
                            text: '@',
                            title: '发送邮件',
                            icon: '',
                            classname: 'btn btn-xs btn-success   btn-click',
                            click: function (data,row) {
                                var that = this;
                                var title = __('发邮件给联系人：')+row.name;
                                var url = $(that).attr('href');
                                var data = {types:'contacts',typesid:row.id};
                                parent.Fast.api.open(url+"?data="+encodeURI(JSON.stringify(data)), title, data);

                            },
                            url:'facrm/apps/email/send',

                        },
                        {
                            name: 'sms',
                            text: '',
                            title: '发送短息',
                            icon: 'fa fa-envelope-o fa-fw',
                            classname: 'btn btn-xs btn-success   btn-click',
                            click: function (data,row) {
                                var that = this;
                                var title = __('发短息给联系人：')+row.name;
                                var url = $(that).attr('href');

                                var data = {types:'contacts',typesid:row.id};
                                parent.Fast.api.open(url+"?data="+encodeURI(JSON.stringify(data)), title, data);
                            },
                            url:'facrm/apps/sms/send',

                        },

                    ],
                    formatter: Table.api.formatter.operate
                },

            ];
            if (Config.fields&&Object.keys(Config.fields).length > 0){
                var fields=JSON.parse(Config.fields);
                var  start=15;
                for (var i=0;i<fields.length;i++)
                {
                    if (fields[i].hasOwnProperty('formatter'))
                        fields[i].formatter=eval(fields[i].formatter);
                    if (fields[i].hasOwnProperty('events'))
                        fields[i].events=eval(fields[i].events);
                    columnss.splice(start+i,0,fields[i]);
                }
            }
            contact.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                toolbar: '#toolbar',
                queryParams: function (params) { // 请求服务器数据时发送的参数，可以在这里添加额外的查询参数，返回false则终止请求
                    //params.filter='{"customer_id":'+customer_id+'}';//只是查当前客户的联系人
                    return params
                },
                columns: [
                    columnss
                ],
                onLoadSuccess: function () {
                    // 载入成功时执行
                    loadSuccess("customer_contacts")
                },
                onColumnSwitch: function () {
                    // 切换列时执行columnSwitch方法
                    columnSwitch("customer_contacts","customer_contacts_table")
                },
                //启用固定列
                fixedColumns: true,
                //固定右侧列数
                fixedRightNumber: 1,
                searchFormVisible:true, //打开搜索
            });
            // 初始化表格
            contact.bootstrapTable();
            Table.api.bindevent(contact);//当内容渲染完成后
            // 绑定TAB事件
            $('.panel-heading ul[data-field] li a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var field = $(this).closest("ul").data("field");
                var value = $(this).data("value");
                $(".commonsearch-table input[name="+field+"]").val(value);
                return false;
            });
            //批量发邮件
            $(".btn-send-emails").click(function () {
                var that = this;
                var title = $(that).data('title') || $(that).attr("title") || __('批量发邮件');
                var url = $(that).data('url');
                var data = $(that).data() || {};
                delete data.title,data.url;
                var ids = Table.api.selectedids(contact);
                if (ids.length <=0) {
                    return;
                }
                data.typesid=ids;
                parent.Fast.api.open(url+"?data="+encodeURI(JSON.stringify(data)), title, data);
            });
        },
        add: function () {
            Controller.api.bindevent();

        },
        edit: function () {
            Controller.api.bindevent();
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/customer/contacts/recyclebin',
                }
            });


            var table = $("#table");
            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
            
                $(".commonsearch-table select[name=scene_id]").val(1);

            });
            var columnss=[

                {
                    field: 'operate',
                    width: '130px',
                    title: __('Operate'),
                    table: table,
                    events: Table.api.events.operate,
                    buttons: [
                        {
                            name: 'Restore',
                            text: __('Restore'),
                            classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                            icon: 'fa fa-rotate-left',
                            url: 'facrm/customer/contacts/restore',
                            refresh: true
                        },
                        {
                            name: 'Destroy',
                            text: __('Destroy'),
                            classname: 'btn btn-xs btn-danger btn-ajax  btn-destroyit',
                            icon: 'fa fa-times',
                            url: 'facrm/customer/contacts/destroy',
                            refresh: true
                        }
                    ],
                    formatter: Table.api.formatter.operate
                },
                {field: 'customer_id', title: __('客户ID')},
                {field: 'name', title: __('姓名')},
                {field: 'mobile', title: __('手机')},
                {field: 'telephone', title: __('电话')},
                {field: 'owner_user.nickname', title: __('负责人'), operate: false, search: false,
					addclass: 'selectpage',
					extend: 'data-source="facrm/common/selectpage/model/admin?type=children" data-field="nickname"'},
                {field: 'owner_user_id', title: __('负责人'), visible: false,
					addclass: 'selectpage',
					extend: 'data-source="facrm/common/selectpage/model/admin?type=children" data-field="nickname"'},

            ];
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    columnss
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                contacts_id=Config.contacts_id;
                if ("undefined" == typeof Config.contacts_id){
                    contacts_id=0;
                }
                Fast.api.ajax({
                    url: 'facrm/fields/get_fields_html',
                    data: {source: 'customer_contacts', 'id': contacts_id}
                }, function (data) {
                    $("#extend").html(data.html);
                    Form.api.bindevent($("#extend"));
                    return false;
                });

                //云呼
                $(".cloudcall").click(function () {
                    var that = this;
                    var type = $(that).data('type');
                    var typeid = $(that).data('typeid');
                    var name = $(that).data('name');
					var field = $(that).data('field');

					Fast.api.ajax({
						url: 'facrm/setting/cloudcall/call',
						data: {type: type, typeid: typeid,field:field,name:name}
                    }, function (data) {
                        Toastr.success("呼叫成功！");
                        return false;
                    });
                });
            },
            formatter: {
                thumb: function (value, row, index) {
                    if (!value) return '';
                    value = value === null ? '' : value.toString();
                    var arr = value.split(',');
                    var html = [];
                    $.each(arr, function (i, value) {
                        var reg = /\.(png|jpg|gif|jpeg|webp)$/;
                        if (reg.test(value)) {
                            html.push( '<a href="' +  Fast.api.cdnurl(value) + '" target="_blank"><img src="'+  Fast.api.cdnurl(value)  + '" alt="" style="max-height:90px;max-width:120px"></a>');
                        } else {
                            if (row.imagetype==undefined)row.imagetype =/[^\.]+$/.exec(value);
                            html.push('<a href="' + Fast.api.cdnurl(value) + '" target="_blank"><img src="' + Fast.api.fixurl("ajax/icon") + "?suffix=" + row.imagetype + '" alt="" style="max-height:90px;max-width:120px"></a>');
                        }
                    });
                    return html.join(' ');
                },
            }
        }
    };
    return Controller;
});